import { ApiActionType, channelType } from "@/types/data";
import { ChannelAction, RootThunkAction } from "@/types/store";
import request from "@/utils/request";
import { hasToken } from "@/utils/storage";
import { getchannels, setchannels } from "@/utils/storagechannel";
import { Dispatch } from "react";

export const getchannel = (): RootThunkAction => {
    return async (dispatch: Dispatch<ChannelAction>) => {
        if (hasToken()) { //如果用户登录了 就发请求 存数据
            const res = await request.get<ApiActionType<{ channels: channelType[] }>>('/user/channels')
            console.log(res, 'resrse');
            dispatch({
                type: 'channel/get_channel',
                payload: res.data.data.channels
            })
        } else {//如果没有用户登录 就从本地拿缓存了的数据
            const channels = getchannels()
            if (channels.length) { //如果本地有数据 就存到reducer
                dispatch({
                    type: 'channel/get_channel',
                    payload: channels
                })
            } else {//如果本地没有数据就请求 默认的数据
                const res = await request.get<ApiActionType<{ channels: channelType[] }>>('/user/channels')
                const newchannel = res.data.data.channels
                dispatch({
                    type: 'channel/get_channel',
                    payload: newchannel
                })
                setchannels(newchannel)
            }
        }
    }
}

export const setActive = (id: string): ChannelAction => {
    return {
        type: 'channel/set_active',
        payload: id
    }
}

export const setAllchannel = ():RootThunkAction=>{
  return async(dispatch:Dispatch<ChannelAction>)=>{
  const res = await request.get<ApiActionType<{ channels: channelType[] }>>('/channels')
  console.log(res,'99999');
  dispatch({
      type:'channel/saveAllChannels',
      payload:res.data.data.channels
  })
  }
}

export const addChannel = (channel:channelType):RootThunkAction=>{
 return async(dispatch,getState)=>{
    const channels=getState().channel.channels
     if(hasToken()){
    const res = await request.patch('/user/channels',{
        channels: [channel]
    })
    console.log(res,'add');
     }else{ //没有登录就存到本地
      setchannels([...channels,channel])
     }
     dispatch({
        type:'channel/addChannels',
        payload:[...channels,channel]
    })
     dispatch(getchannel())
 }
}
export const deletChannel = (id:number):RootThunkAction=>{
 return async(dispatch,getState)=>{
    const channels=getState().channel.channels   
     const Deletchannel= channels.filter(item=>item.id!==id)
     if(hasToken()){
    const res = await request.delete('/user/channels', {
        data: {
          channels: [id]
        }
      })
    console.log(res,'delet');
     }else{ //没有登录就存到本地
      setchannels(Deletchannel)
     }
    dispatch(getchannel())
 }
}